<?php

namespace bc\model\marquee;

use bc\ar\MActiveRecord;

class MarqueeModel extends MActiveRecord
{
	
	public static function tableName()
	{
		return '{{%marquee}}';
	}
	
	
	protected function getBlockTable()
	{
		return BlockModel::getTableSchema()->name;
	}
	
	/**
	 *	查询数据表的信息
	 * @param array $params
	 * @param integer $page
	 * @param integer $pageSize
	 */
	public function getBackendList($params, $page = null, $pageSize = null)
	{
		
		$ar = $this->find ()->select(self::getTableSchema()->name . '.*, ' . $this->getBlockTable() . '.block_name')
				->leftJoin('bc_marquee_block', 'bc_marquee_block'. '.block_id = ' . self::getTableSchema()->name . '.block_id')
				->where($params);
		if ($page && $pageSize)
		{
			$offset = $this->getOffset ( $page, $pageSize );
			$ar->offset($offset)->limit($pageSize);
		}
	
		if($this->sort == null)
			$ar->orderBy ( $this->autoId . ' DESC' );
		else
			$ar->orderBy ( $this->sort );
		return $ar->asArray()->all();
	}
        
        
        
        public function getMarqueeList($params, $page = null, $pageSize = null)
    {    
                $this->sort = "bc_marquee.sort  asc";
                $this->columns = "bc_marquee.id,bc_marquee.image,bc_marquee.link,bc_marquee.description";
                $ar = $this->find ()->select($this->columns) ->where($params);
                if($this->sort == null)
			$ar->orderBy ( $this->autoId . ' desc' );
		else
			$ar->orderBy ( $this->sort );
                return $ar->asArray()->all();
    } 
        
    
	
	/**
	 *
	 * @param array $condition
	 * @return integer
	 */
	public function getBackendTotal($condition)
	{
		if(!empty($condition))
			return $this->find()->where($condition)->count();
		else
			return 0;
	}
	
	
	/**
	 * 开启事务方式执行
	 * $data sort
	 * $data primary key 
	 */
	public function setSort(array $data)
	{
		$transaction = $this->getDb()->beginTransaction();
		try
		{
			foreach ($data as $object)
			{
				$sql = 'UPDATE ' . self::getTableSchema ()->name . " SET `sort` = {$object->sort} WHERE id = {$object->id}" ;
				$this->getDb()->createCommand($sql)->execute();
			}
		
			$transaction->commit();
			return true;
		}
		catch (\Exception $e)
		{
			$transaction->rollBack();
			throw $e;
		}
	}
}

